package com.hpf.consumer.controller;

import com.hpf.commons.pojo.Payment;
import com.hpf.commons.utils.CommonResult;
import com.hpf.consumer.lb.LoadBalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @description:
 * @datetime: 2020/8/18 22:25
 * @author: huangpengfei
 */
@Slf4j
@RestController
public class OrderController {

    /**
     *  按照服务名去访问，一个服务名可能有多台机器
     */
    private static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;


    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment) {
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    @GetMapping("/consumer/payment/entity/get/{id}")
    public CommonResult getPaymentEntityById(@PathVariable("id") Long id) {
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        if(forEntity.getStatusCode().is2xxSuccessful()){
            log.info("返回的状态码：{}",forEntity.getStatusCode());
            return forEntity.getBody();
        }
        return new CommonResult(444,"获取信息失败");
    }

    @Resource
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalance loadBalance;

    @GetMapping("/consumer/payment/port")
    public String getPort() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if(instances.isEmpty() || null == instances){
            return "";
        }
        ServiceInstance serviceInstance = loadBalance.instances(instances);
//        URI uri = serviceInstance.getUri();
        String serviceId = serviceInstance.getServiceId();
        return restTemplate.getForObject("http://"+ serviceId + "/payment/port",String.class);
    }

    @GetMapping("/consumer/payment/zipkin")
    public String zipkin() {
        return restTemplate.getForObject(PAYMENT_URL + "/payment/zipkin", String.class);
    }
}
